package com.xavier.dong.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter 子类
 * <p>
 * HttpObject 客户端和服务器端 相互 通讯的数据 被封装成 HttpObject
 *
 * @author XavierDong
 **/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    /**
     * 读取 客户端数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        // 判断 msg 是不是 HttpRequest 请求
        if (msg instanceof HttpRequest) {

            System.out.println("pipeline hashcode=" + ctx.pipeline().hashCode() + " TestHttpServerHandler hashcode=" + this.hashCode());

            System.out.println("msg 类型=" + msg.getClass());
            System.out.println("客户端地址： " + ctx.channel().remoteAddress());


            // 获取到
            HttpRequest httpRequest = (HttpRequest) msg;
            // 获取 URI 过滤 指定的资源
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了 favicon.ico，不做响应");
                return;
            }


            // 回复信息 给 浏览器 [Http 协议]
            ByteBuf content = Unpooled.copiedBuffer("hello，我是服务器.", CharsetUtil.UTF_8);

            // 构造一个 Http 的响应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 将 构建好的 返回
            ctx.writeAndFlush(response);
        }

    }
}
